<style scoped>
.cardReaderTest {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.top_msg {
  height: 66px;
  padding-top: 15px;
  border-bottom: 2px solid #f4f4f4;
  white-space: nowrap;
}
.top_msg p {
  display: inline-block;
  text-align: right;
  line-height: 30px;
  margin-right: 0.5vw;
}

.btns {
  width: 100%;
  height: 32px;
  margin: 15px 0;
}
.rfidList {
  border-top: 2px solid #f4f4f4;
}
.rfidList > div {
  display: inline-block;
  width: 50%;
  overflow: auto;
  height: 80vh;
}
.content1 {
  border-right: 2px solid #f4f4f4;
}
</style>

<style>
.cardReaderTest .el-input__icon {
  line-height: 30px;
}
.cardReaderTest .el-input__inner,
.cardReaderTest .el-input {
  height: 30px;
  margin-right: 0.5vw;
}
.cardReaderTest .el-input__inner {
  padding: 0 5px;
}
.cardReaderTest .el-select {
  width: 7vw;
  margin-right: 0.5vw;
}
.cardReaderTest .el-button {
  margin: 0 10px 0 0;
}
.cardReaderTest .el-alert {
  width: 30%;
  border-radius: 50px;
  top: -40px;
  left: 550px;
  padding: 2px 16px;
}
.cardReaderTest .el-alert__closebtn {
  font-size: 25px;
}
.cardReaderTest .el-alert__title {
  font-size: 16px;
}
.cardReaderTest .el-alert .el-alert__description {
  margin: 0;
  font-size: 14px;
}
.el-autocomplete-suggestion li {
  padding: 0 5px;
}
</style>

<template>
  <div class="cardReaderTest" v-loading.fullscreen.lock="fullscreenLoading">
    <!-- UHF_读卡器测试R2000 -->
    <div class="top_msg">
      <p>服务器地址</p>
      <el-autocomplete
        v-model="rfidType"
        :fetch-suggestions="querySearch"
        style="width: 2.5vw; margin-right: 10px"
        @select="handleSelect"
      >
      </el-autocomplete>
      <el-input v-model="serverAddress1" style="width: 7vw"></el-input>
      <el-input v-model="serverAddress2" style="width: 3vw"></el-input>
      <el-button @click="save">保存</el-button>
      <el-button type="primary" @click="connection" :disabled="isConnection"
        >连接</el-button
      >
      <el-button @click="disconnect" :disabled="!isConnection">断开</el-button>
      <p>命令</p>
      <el-input
        v-model="command1"
        style="width: 4.5vw"
        @blur="commandBlur"
      ></el-input>
      <el-input
        v-model="command2"
        style="width: 9.5vw"
        @blur="commandBlur"
      ></el-input>
      <el-input v-model="command3" style="width: 1.5vw"></el-input>
      <el-button type="primary" @click="send" :disabled="!isConnection"
        >发送</el-button
      >
      <p>命令套字</p>
      <el-input v-model="command" disabled style="width: 14vw"></el-input>
      <el-button type="primary">发送(TID)</el-button>
      <p>天线开关</p>
      <el-select v-model="antenna" multiple collapse-tags>
        <el-option
          v-for="item in antennaList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>

    <div class="btns">
      <el-button icon="el-icon-delete" type="primary" @click="clear"
        >清空所有</el-button
      >
      <el-alert
        v-show="isFinish"
        title="完成读卡"
        :description="description"
        type="success"
        show-icon
      >
      </el-alert>
    </div>
    <div class="rfidList">
      <div class="content1">
        <div v-for="i in tableData1" :key="i">{{ i }}</div>
      </div>
      <div class="content2">
        <div v-for="i in tableData2" :key="i">{{ i }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getUhfTest,
  postUhfTest,
  putUhfTest,
  checkCode
} from '../../../network/rfid'
import {
  connectStatus,
  UHFConnection,
  sendOrder,
  orderList,
  close
} from '../../../network/rfid'
import { internetProtocol } from '../../../config/ip'

import enterUp from '../../../components/mixins/enterUp'

export default {
  name: 'cardReaderTest',
  mixins: [enterUp],
  created() {
    this.getList()
  },
  data() {
    return {
      inpList: [],
      socketId: '',
      ws: {},

      rfidType: '',
      rfidTypeList: [],
      serverAddress1: '',
      serverAddress2: '',
      command: '',
      command1: '',
      command2: '',
      command3: '',
      antenna: [],
      antennaList: [
        // {value:'无',label: '无'},
        { value: '00', label: '00' },
        { value: '01', label: '01' },
        { value: '02', label: '02' },
        { value: '03', label: '03' }
      ],
      tableData1: [],
      tableData2: [],

      isFinish: false,
      isConnection: false,
      description: '',

      fullscreenLoading: false,
      currentCommand: {},

      loading: {}
    }
  },
  methods: {
    save() {
      if (!this.antenna.length) {
        this.$alert('请选择天线开关', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.rfidTypeList.length) {
        this._postUhfTest()
      } else {
        let exist = 0
        for (const i of this.rfidTypeList) {
          if (i.equipmentCabinetNo == this.rfidType) {
            exist = 1
            if (
              i.ip != this.serverAddress1 ||
              i.port != this.serverAddress2 ||
              i.antenna != this.antenna
            ) {
              let antennaSwitch = [4, 4, 4, 4]
              if (this.antenna.indexOf('00') != -1) {
                antennaSwitch[0] = 0
              }
              if (this.antenna.indexOf('01') != -1) {
                antennaSwitch[1] = 1
              }
              if (this.antenna.indexOf('02') != -1) {
                antennaSwitch[2] = 2
              }
              if (this.antenna.indexOf('03') != -1) {
                antennaSwitch[3] = 3
              }

              i.equipmentCabinetNo = this.rfidType
              i.ip = this.serverAddress1
              i.port = this.serverAddress2
              i.antennaSwitch = String(antennaSwitch)
              putUhfTest(JSON.stringify(i)).then((res) => {
                if (res.data.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  this.getList()
                } else {
                  this.$message.error('修改失败')
                }
              })
            }
            this.$message.warning('未有任何修改')
            break
          }
        }
        if (!exist) this._postUhfTest()
      }
    },
    connection() {
      if (!this.rfidType || !this.serverAddress1 || !this.serverAddress2) {
        this.$alert('服务器地址不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }

      // return
      // socketId赋值
      this.socketId = Math.ceil(Math.random() * 1000000) + ''
      this.ws = new WebSocket(
        `wss://${internetProtocol}/webSocket/${this.socketId}`
      )
      this.ws.onopen = (e) => {
        // console.log(e)
        // 这也是后端的接口，建立读卡器链接
        UHFConnection({
          host: this.serverAddress1,
          port: Number(this.serverAddress2),
          socketId: this.socketId
        })
        setTimeout(() => {
          connectStatus({ socketId: this.socketId }).then((res) => {
            if (res.data.code == 200) {
              this.$message.success('读卡器连接成功')
              this.isConnection = true
            } else {
              this.$message.error('读卡器连接失败')
            }
          })
        }, 1500)
      }
      this.ws.onmessage = (e) => {
        // console.log(e)
        if (e.data == '连接成功') return
        let obj = e.data
        obj = JSON.parse(obj)
        if (obj.endCommand) {
          this.$message.success('读卡完成')
          this.ws.close()
          this.isFinish = true
          this.isConnection = false
          this.description = `本次获取Tag Count: ${this.tableData1.length} Total times(ms): ${e.timeStamp}`
          this.loading.close()
        }

        if (obj.isConnectError) {
          // 连接异常
          this.$message.error(
            `请检查路由器外网IP是否与此IP一致 ：${obj.connectTimeOutIp}`
          )
          this.isFinish = true
          this.isConnection = false
          this.loading.close()
          this.ws.close()
        }

        if (obj.validShowCode) {
          this.tableData1.unshift(obj.validShowCode)
        }
        if (obj.otherErrorRFID) {
          this.tableData1.unshift(obj.otherErrorRFID + '其他错误')
        }
        if (obj.antennaErrorRFID) {
          this.tableData1.unshift(
            obj.antennaErrorRFID + '天线错误' + obj.antennaErrorIndex
          )
        }
        // this.fullscreenLoading = false
      }
      this.ws.onclose = () => {
        // console.log("调转连接已关闭")
        close({ socketId: this.socketId })
      }
      this.ws.onerror = (e) => {
        console.log(e)
      }
    },
    _postUhfTest() {
      let antennaSwitch = [4, 4, 4, 4]
      if (this.antenna.indexOf('00') != -1) {
        antennaSwitch[0] = 0
      }
      if (this.antenna.indexOf('01') != -1) {
        antennaSwitch[1] = 1
      }
      if (this.antenna.indexOf('02') != -1) {
        antennaSwitch[2] = 2
      }
      if (this.antenna.indexOf('03') != -1) {
        antennaSwitch[3] = 3
      }
      postUhfTest({
        equipmentCabinetNo: this.rfidType,
        ip: this.serverAddress1,
        port: this.serverAddress2,
        antennaSwitch: String(antennaSwitch)
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.getList()
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    disconnect() {
      this.ws.close()
    },
    send() {
      this.clear()
      // console.log(this.command)
      connectStatus({ socketId: this.socketId }).then((r) => {
        if (r.data.code == 200) {
          sendOrder({
            command: this.command,
            connectId: this.socketId
          })
          this.loading = this.$loading({
            lock: true,
            text: '读卡中...',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0)'
          })
        } else {
          this.$message.error('连接已断开，请重新连接')
          this.isConnection = false
        }
      })
    },
    clear() {
      this.tableData1 = []
      this.tableData2 = []
      this.isFinish = false
    },

    querySearch(queryString, cb) {
      cb(this.rfidTypeList)
    },
    handleSelect(item) {
      // console.log(item)
      this.currentCommand = item
      this.serverAddress1 = item.ip
      this.serverAddress2 = item.port
      this.command1 = item.testHead
      this.command2 = item.command2
      this.command3 = item.command3
      this.command = item.testHead + item.testBody
      this.antenna = item.antenna
      this.isFinish = false
    },

    commandBlur() {
      if (
        this.currentCommand.testHead != this.command1 ||
        this.currentCommand.command2 != this.command2
      ) {
        checkCode({ command: this.command1 + this.command2 }).then((res) => {
          if (res.data.data) {
            let str = res.data.data
            this.currentCommand.testHead = str.slice(0, 8)
            this.currentCommand.testBody = str.slice(8)
            this.currentCommand.command2 = str.slice(8, -2)
            this.currentCommand.command3 = str.slice(-2)
            this.command =
              this.currentCommand.testHead + this.currentCommand.testBody
            // console.log(this.currentCommand)
            this.command1 = this.currentCommand.testHead
            this.command2 = this.currentCommand.command2
            this.command3 = this.currentCommand.command3

            for (const i of this.rfidTypeList) {
              if (i.equipmentCabinetNo == this.rfidType) {
                i.testHead = this.command1
                i.testBody = this.command2 + this.command3

                let antennaSwitch = [4, 4, 4, 4]
                if (this.antenna.indexOf('00') != -1) {
                  antennaSwitch[0] = 0
                }
                if (this.antenna.indexOf('01') != -1) {
                  antennaSwitch[1] = 1
                }
                if (this.antenna.indexOf('02') != -1) {
                  antennaSwitch[2] = 2
                }
                if (this.antenna.indexOf('03') != -1) {
                  antennaSwitch[3] = 3
                }

                i.equipmentCabinetNo = this.rfidType
                i.ip = this.serverAddress1
                i.port = this.serverAddress2
                i.antennaSwitch = String(antennaSwitch)

                putUhfTest(JSON.stringify(i)).then((res) => {
                  if (res.data.code == 200) {
                    this.$message({
                      message: '修改成功',
                      type: 'success'
                    })
                    this.getList()
                  } else {
                    this.$message.error('修改失败')
                  }
                })
              }
            }
          }
        })
      }
    },

    getList() {
      getUhfTest().then((res) => {
        this.rfidTypeList = res.data.data
        this.rfidTypeList.forEach((e) => {
          // e.testHead = e.testHead.toUpperCase()
          // e.testBody = e.testBody.toUpperCase()
          e.value = e.equipmentCabinetNo
          e.command2 = e.testBody.slice(0, -2)
          e.command3 = e.testBody.slice(-2)

          e.antenna = []
          if (e.antennaSwitch.indexOf('0') != -1) {
            e.antenna.push('00')
          }
          if (e.antennaSwitch.indexOf('1') != -1) {
            e.antenna.push('01')
          }
          if (e.antennaSwitch.indexOf('2') != -1) {
            e.antenna.push('02')
          }
          if (e.antennaSwitch.indexOf('3') != -1) {
            e.antenna.push('03')
          }
          // if (!e.antenna.length) e.antenna = ['无']
        })
      })
      this.inpList = this.getInput()
    }
  },
  beforeDestroy() {
    if (this.ws.readyState == 1) this.ws.close()
    // JSON.stringify(this.ws) == '{}' || this.ws.close()
  }
}
</script>
